/**
 * @author hewei
 * @version 1.0
 * @description: 135. 分发糖果
 * @date 2022/7/27 15:06
 */

public class Candy {

    public int candy1(int[] ratings) {
        int n = ratings.length;
        int[] temp = new int[n];
        temp[0] = 1;
        for (int i = 1; i < n; i++) {
            if (ratings[i] > ratings[i - 1]) {
                temp[i] = temp[i - 1] + 1;
            } else temp[i] = 1;
        }
        int r = 1;
        int ans = temp[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1]) {
                r += 1;
            } else r = 1;
            ans += Math.max(temp[i], r);
        }
        return ans;
    }

    public int candy(int[] ratings) {
        int ans = 1, pre = 1, inc = 1, des = 0;
        for (int i = 1; i < ratings.length; i++) {
            if (ratings[i] >= ratings[i - 1]) {
                des = 0;
                pre = ratings[i] == ratings[i - 1] ? 1 : pre + 1;
                ans += pre;
                inc = pre;
            } else {
                ++des;
                if (des == inc) ++des;
                pre = 1;
                ans += des;
            }
        }
        return ans;
    }
}
